use std::ffi::CString;
use std::io::{self, Write};
use std::os::unix::io::AsRawFd;
use std::os::unix::net::{SocketAddr, ToSocketAddrs};
use std::os::unix::net::TcpListener;
use std::os::unix::net::TcpStream;
use std::os::unix::fs::{unlink, open};
use std::os::unix::fs::{ftruncate, mmap, munmap};
use std::os::unix::io::{self, FromRawFd};
use std::os::unix::prelude::RawFd;
use std::os::unix::fs::{close, read, write};
use std::os::unix::process::{fork, waitpid, exit};
use std::ptr;

// 消息结构
struct message {
    written: i32,
    text: [u8; 1024 - std::mem::size_of::<i32>()],
}

// 服务端代码：
fn server(shm_fd: RawFd) {
    // 将共享内存映射到进程地址空间
    let shm = unsafe { mmap(ptr::null_mut(), SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0) };
    if shm.is_null() {
        perror("mmap");
        exit(EXIT_FAILURE);
    }

    // 创建epoll实例
    let epoll_fd = unsafe { epoll_create1(0) };
    if epoll_fd < 0 {
        perror("epoll_create1");
        exit(EXIT_FAILURE);
    }

    // 创建epoll事件
    let mut ev = epoll_event {
        events: EPOLLIN,
        data: epoll_data {
            fd: shm_fd,
        },
    };

    // 注册epoll事件
    let res = unsafe { epoll_ctl(epoll_fd, EPOLL_CTL_ADD, shm_fd, &mut ev) };
    if res < 0 {
        perror("epoll_ctl: add");
        exit(EXIT_FAILURE);
    }

    loop {
        // 等待epoll事件
        let mut events = [ev; 1];
        let nfds = unsafe { epoll_wait(epoll_fd, &mut events, 1, 500) };
        if nfds < 0 {
            perror("epoll_wait");
            exit(EXIT_FAILURE);
        }

        // 读取共享内存
        let msg = unsafe { &*(shm as *mut message) };
        if msg.written != 0 {
            println!("Server received: {}", std::str::from_utf8(&msg.text[..]).unwrap());
            msg.written = 0; // 设置共享内存为可写状态
        }
    }
}

// 客户端代码：
fn client(shm_fd: RawFd) {
    loop {
        // 创建共享内存映射到进程地址空间
        let shm = unsafe { mmap(ptr::null_mut(), SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0) };
        if shm.is_null() {
            perror("mmap");
            exit(EXIT_FAILURE);
        }

        // 等待共享内存可写
        let msg = unsafe { &mut *(shm as *mut message) };
        while msg.written != 0 {
            sleep(1); // 等待服务器读取消息
        }

        println!("Enter some text: ");
        let mut buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();

        let trimmed = buffer.trim_end();
        let trimmed = trimmed.as_bytes();
        unsafe {
            std::ptr::copy_nonoverlapping(trimmed.as_ptr(), msg.text.as_mut_ptr(), trimmed.len());
        }
        msg.written = 1; // 更新标志，标识已写入数据
    }
}

fn main() {
    let shm_name = CString::new("shm_example").unwrap();

    // 打开共享内存对象
    let shm_fd = unsafe { open(shm_name.as_ptr(), O_CREAT | O_RDWR, 0666) };
    if shm_fd < 0 {
        perror("shm open");
        return;
    }

    // 设置共享内存大小
    let res = unsafe { ftruncate(shm_fd, SHM_SIZE) };
    if res < 0 {
        perror("ftruncate");
        return;
    }

    let pid = unsafe { fork() };
    if pid < 0 {
        perror("fork");
        return;
    }

    if pid == 0 {
        // 子进程 - 客户端
        client(shm_fd);
    } else {
        // 父进程 - 服务器
        server(shm_fd);
    }

    // 等待子进程结束
    let mut status = 0;
    unsafe { waitpid(pid, &mut status, 0) };

    // 断开共享内存映射
    unsafe { munmap(ptr::null_mut(), SHM_SIZE) };

    // 删除共享内存对象
    unsafe { unlink(shm_name.as_ptr()) };
}
